package com.mengchengnet.chaperonage.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.mengchengnet.chaperonage.BaseActivity;
import com.mengchengnet.chaperonage.BaseFragment;
import com.mengchengnet.chaperonage.R;
import com.mengchengnet.chaperonage.adapter.BaseInfoAdapter;
import com.mengchengnet.chaperonage.adapter.ChaperonageAdapter;
import com.mengchengnet.chaperonage.domain.base.BaseInfo;
import com.mengchengnet.chaperonage.domain.base.Chaperonage;
import com.mengchengnet.chaperonage.ui.activity.MainActivity;
import com.mengchengnet.chaperonage.ui.activity.OrderActivity;
import com.mengchengnet.chaperonage.util.PreferenceUtil;
import com.mengchengnet.chaperonage.util.Url;
import com.mengchengnet.chaperonage.util.ViewUtil;
import com.mengchengnet.chaperonage.view.DropDownMenu;
import com.mengchengnet.chaperonage.view.refreshableListView.RefreshableListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ChaperonageFragment extends BaseFragment  {
    private View view;
    private DropDownMenu ddmPrice;
    private DropDownMenu ddmAge;
    private DropDownMenu ddmSort;
    private DropDownMenu ddmBusy;

    private RefreshableListView rlvChaperonage;
    private ChaperonageAdapter chaperonageAdapter;
    private ArrayList<Chaperonage> chaperonageList;
    private RequestQueue requestQueue;
    private static final String TAG = "ChaperonageFragment";
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            chaperonageAdapter = new ChaperonageAdapter(getContext(), R.layout.item_chaperonage_listview, chaperonageList);
            rlvChaperonage.setPullLoadEnable(false);
            rlvChaperonage.setPullRefreshEnable(false);
            rlvChaperonage.setAdapter(chaperonageAdapter);
            rlvChaperonage.setRefreshableListViewListener(new RefreshableListView.RefreshableListViewListener() {
                @Override
                public void onRefresh() {

                }

                @Override
                public void onLoadMore() {

                }
            });
            rlvChaperonage.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    String name=chaperonageList.get(position-1).getName();
                    String address=chaperonageList.get(position-1).getHometown();
                    String age=chaperonageList.get(position-1).getAge();
                    String workAge=chaperonageList.get(position-1).getWorkTime();
                    String head=chaperonageList.get(position-1).getPhoto();
                    String evaulate=chaperonageList.get(position-1).getDescription();
                    String price=chaperonageList.get(position-1).getPrice();
                    String careId=chaperonageList.get(position-1).getChaperonageId();
                    String commentCount=chaperonageList.get(position-1).getCommentsCount();
                    int starCount=chaperonageList.get(position-1).getRating();

                    Intent intent = new Intent(BaseActivity.currentActivity, OrderActivity.class);
                    intent.putExtra("name",name);
                    intent.putExtra("address",address);
                    intent.putExtra("age",age);
                    intent.putExtra("workAge",workAge);
                    intent.putExtra("head",head);
                    intent.putExtra("evaulate",evaulate);
                    intent.putExtra("price",price);
                    intent.putExtra("careId",careId);
                    intent.putExtra("commentCount",commentCount);
                    intent.putExtra("star",starCount);
                    startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);

                }
            });
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        setHasOptionsMenu(true);
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        if (view == null) {
            view = inflater.inflate(R.layout.fragment_chaperonage, null);
        }
        requestQueue= Volley.newRequestQueue(getActivity());
        List<BaseInfo> priceList = new ArrayList<>();
        priceList.add(new BaseInfo("1", "0元~99元"));
        priceList.add(new BaseInfo("2", "100元~199元"));
        priceList.add(new BaseInfo("3", "200元以上"));

        List<BaseInfo> ageList = new ArrayList<>();
        ageList.add(new BaseInfo("1", "20岁~29岁"));
        ageList.add(new BaseInfo("2", "30岁~39岁"));
        ageList.add(new BaseInfo("3", "40岁以上"));

        List<BaseInfo> sortList = new ArrayList<>();
        sortList.add(new BaseInfo("0", "陪护师"));
        sortList.add(new BaseInfo("1", "月嫂"));
        sortList.add(new BaseInfo("2", "育婴师"));
        sortList.add(new BaseInfo("3", "催乳师"));

        List<BaseInfo> busyList = new ArrayList<>();
        busyList.add(new BaseInfo("0", "男"));
        busyList.add(new BaseInfo("1", "女"));

        final BaseInfoAdapter priceAdapter = new BaseInfoAdapter(getContext(), R.layout.list_item, priceList);
        ddmPrice = (DropDownMenu) view.findViewById(R.id.ddm_price);
        ddmPrice.setAdapter(priceAdapter);
        ddmPrice.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                merchantList.clear();
//                merchantAdapter.notifyDataSetChanged();
//                getMerchantModel.setDistrictId(districtAdapter.getId(position));
//                getMerchantModel.setMerchantName("");
//                getMerchantModel.setPageIndex(1);
//                ViewUtil.showProgressDialog("数据加载中...");
//                HttpService.doGetMerchant(getMerchantModel);
            }
        });

        final BaseInfoAdapter ageAdapter = new BaseInfoAdapter(getContext(), R.layout.list_item, ageList);
        ddmAge = (DropDownMenu) view.findViewById(R.id.ddm_age);
        ddmAge.setAdapter(ageAdapter);
        ddmAge.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                merchantList.clear();
//                merchantAdapter.notifyDataSetChanged();
//                getMerchantModel.setBusinessTypeId(businessTypeAdapter.getId(position));
//                getMerchantModel.setMerchantName("");
//                getMerchantModel.setPageIndex(1);
//                ViewUtil.showProgressDialog("数据加载中...");
//                HttpService.doGetMerchant(getMerchantModel);
            }
        });

        final BaseInfoAdapter sortAdapter = new BaseInfoAdapter(getContext(), R.layout.list_item, sortList);
        ddmSort = (DropDownMenu) view.findViewById(R.id.ddm_sort);
        ddmSort.setAdapter(sortAdapter);
        ddmSort.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                merchantList.clear();
//                merchantAdapter.notifyDataSetChanged();
//                getMerchantModel.setBusinessTypeId(businessTypeAdapter.getId(position));
//                getMerchantModel.setMerchantName("");
//                getMerchantModel.setPageIndex(1);
//                ViewUtil.showProgressDialog("数据加载中...");
//                HttpService.doGetMerchant(getMerchantModel);
            }
        });
        final BaseInfoAdapter busyAdapter = new BaseInfoAdapter(getContext(), R.layout.list_item, busyList);
        ddmBusy = (DropDownMenu) view.findViewById(R.id.ddm_busy);
        ddmBusy.setAdapter(busyAdapter);
        ddmBusy.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                merchantList.clear();
//                merchantAdapter.notifyDataSetChanged();
//                getMerchantModel.setBusinessTypeId(businessTypeAdapter.getId(position));
//                getMerchantModel.setMerchantName("");
//                getMerchantModel.setPageIndex(1);
//                ViewUtil.showProgressDialog("数据加载中...");
//                HttpService.doGetMerchant(getMerchantModel);
            }
        });
        rlvChaperonage= (RefreshableListView) view.findViewById(R.id.lv_merchant);
        chaperonageList = new ArrayList<>();
        //获取陪护列表
        getList();
        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null) {
            parent.removeView(view);
        }

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        MainActivity.toolbarState = MainActivity.TOOLBAR_STYLE_TITLE;
        mainActivity.initToolbar("护工选择");
        //chaperonageList.clear();

    }



    private void getList() {
        ViewUtil.showProgressDialog("加载中...");
        StringRequest request = new StringRequest(Request.Method.POST, Url.GetCareList,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String result) {
                        Log.e(TAG, "获取陪护人员列表返回值："+result );
                        JSONObject jsonObject;
                        try {
                            jsonObject = new JSONObject(result);
                            if (jsonObject.getString("code").equals("00")){
                                ViewUtil.hideProgressDialog();
                                JSONArray array=jsonObject.getJSONArray("careList");
                                for (int i = 0; i <array.length(); i++) {
                                    JSONObject obj=array.getJSONObject(i);

                                    String careName=obj.getString("careName");
                                    String careId=obj.getString("careId");
                                    String careDistance=obj.getString("careDistance");
                                    String brief=obj.getString("brief");
                                    String carePrice=obj.getString("carePrice");
                                    String careIcon=obj.getString("careIcon");
                                    String careHome=obj.getString("careHome");
                                    String careAge=obj.getString("careAge");
                                    String careWorkAge=obj.getString("careWorkAge");
                                    String commentCount=obj.getString("dp_count");
                                    int avg_point=obj.getInt("avg_point");

                                    Chaperonage chaperonage = new Chaperonage();
                                    chaperonage.setAge(careAge);
                                    chaperonage.setCommentsCount(commentCount);
                                    chaperonage.setDescription(brief);
                                    chaperonage.setDistance(careDistance);
                                    chaperonage.setHometown(careHome);
                                    chaperonage.setName(careName);
                                    chaperonage.setPhoto(careIcon);
                                    chaperonage.setPrice(carePrice);
                                    chaperonage.setRating(avg_point);
                                    chaperonage.setWorkTime(careWorkAge);
                                    chaperonage.setChaperonageId(careId);
                                    chaperonageList.add(chaperonage);

                                }

                                handler.sendEmptyMessage(0);

                            }
                            else {
                                Toast.makeText(getContext(), "陪护人员获取失败", Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError arg0) {
                Toast.makeText(getContext(), "网络异常请稍后重试！", Toast.LENGTH_SHORT).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("version", PreferenceUtil.getString(getContext(),"versionCode"));
                map.put("personType", "0");
                map.put("latitude", PreferenceUtil.getString(getContext(),"Latitude"));
                map.put("longitude", PreferenceUtil.getString(getContext(),"Longitude"));
                map.put("price", "0");
                map.put("workAge", "0");
                map.put("sex", "0");
                return map;
            }
        };
        request.setTag("GetFenZu");
        request.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, // 默认超时时间，应设置一个稍微大点儿的
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, // 默认最大尝试次数
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        requestQueue.add(request);

    }

}
